package com.icesoft.core.common.util;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HmacSha1Utils {
	private static final String ALGORITHM = "HmacSHA1";

	public static SecretKeySpec getSecretKeySpec(String key) {
		byte[] keyByte = key.getBytes(StandardCharsets.UTF_8);
		return new SecretKeySpec(keyByte, ALGORITHM);
	}

	public static byte[] doFinal(SecretKeySpec secretKey, byte[] data) {
		return createMac(secretKey).doFinal(data);
	}

	public static byte[] doFinal(String key, byte[] data) {
		return doFinal(getSecretKeySpec(key), data);
	}

	private static Mac createMac(SecretKeySpec secretKey) {
		Mac mac;
		try {
			mac = Mac.getInstance(ALGORITHM);
			mac.init(secretKey);
		} catch (GeneralSecurityException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
		return mac;
	}
}
